package com.study.controller;

import com.study.domain.MyUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/hello3")
public class HelloController3 {
    Logger logger = LoggerFactory.getLogger(HelloController3.class);
    @Value("$M{name}")
    private String name;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    }

    @RequestMapping(value = "/test3",method = RequestMethod.GET)
    @ResponseBody
    public void printWelcome(ModelMap model,HttpServletResponse response,HttpServletRequest request) throws IOException {
       /* MyUser user = (MyUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        logger.info(user.getUsername()+","+user.getNick()+","+user.getPhone());*/
        //model.addAttribute("message", "Hello world!");
        response.setHeader("Access-Control-Allow-Origin", "*");
        //根据html指定的jsonp回调函数的参数名，获取回调函数的名称
        //callbackName的值其实就是：success_jsonpCallback
        String callBackName =request.getParameter("jsonPCallback");

        String jsonStr = "{\"name\":\"张三\",\"age\":28}";
        String renderStr = callBackName+"("+jsonStr+")"; //最终返回的数据为：success_jsonpCallback({"name":"张三","age":28})

        response.setContentType("text/plain;charset=UTF-8");
        response.getWriter().write(renderStr);
        response.getWriter().flush();
        try {
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return ;
    }
}